package ru.ya.kolemik.servcmd.servs;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ru.ya.kolemik.servcmd.AbstractServ;
import ru.ya.kolemik.servcmd.MainApp;
import ru.ya.kolemik.servcmd.View;

public class Auth extends AbstractServ {
    
    public static final String userParamater = "user";
    public static final String passwordParamater = "password";
    public static final String sessionAttribute = "user";
    public static final String redirectToParameter = "redirectTo";
    public static final String actionAttribute = "action";
    public static final String errorMessageAttribute = "error";
    public static final String redirectAttribute = "logoutRedirect";
    
    private final Logger log = Logger.getLogger(this.getClass());
    private MainApp mainApp;
    
    private String checkAuth(String user, String password) {
        if (user.length() != 0 && password.length() != 0) {
            return null;
        } else if (password.length() == 0) {
            return "Пароль должен быть не пустым!";
        } else {
            return "Введите имя пользователя!";
        }
    }
    
    
    public MainApp getMainApp() {
        return mainApp;
    }


    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }

    /**
     * 
     */
    public String doServe(HttpServletRequest request,
            HttpServletResponse response, String command)
            throws ServletException, IOException {
        
        if (request.getSession(false) == null
                || request.getSession(false).getAttribute(sessionAttribute) == null) {
            log.debug("There is no session or user is not logged in.");
            
            String user = request.getParameter(userParamater);
            String password = request.getParameter(passwordParamater);
            String redirectTo = request.getParameter(redirectToParameter);
            
            log.info("REDIRECT TO = " + redirectTo);
            
            if (redirectTo == null) {
                // Мы тут впервые
                redirectTo = command;
                request.setAttribute(redirectToParameter, redirectTo);
                return null;
            } else {
                String error = checkAuth(user, password);
                log.info("Try to auth person with login = " + user
                        + " and password = " + password + " with error = "
                        + error);
                if (error == null) {
                    // Удачно вошли в систему ;)
                    HttpSession session = request.getSession(true);
                    session.setAttribute(sessionAttribute, user);
                    return redirectTo;
                } else {
                    // Выставим сообщение об ошибке
                    request.setAttribute(errorMessageAttribute, error);
                    // Надо снова ввести логин-пароль
                    return null;
                }
            }
        } else {
            // Already logged in
            log.info("Login = " + command);
            if ("logout".equals(command)) {
                log.info("User " + request.getSession().getAttribute(Auth.sessionAttribute) + " was logouted");
                request.getSession().removeAttribute(Auth.sessionAttribute);
                request.setAttribute(redirectAttribute, true);
                return null;
            } else {
                return command;
            }
        }
        
    }
    
    @View
    public void viewHtml(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Object redirect = request.getAttribute(redirectAttribute);
        if (redirect != null && (Boolean)redirect) {
            log.debug("REDIRECT");
            request.getRequestDispatcher("/JSP/logout.jsp").include(request,
                    response);
        } else {
            request.setAttribute(actionAttribute, request.getContextPath() + "/" + getContext(request).getStartCommand());
            request.getRequestDispatcher("/JSP/login.jsp").include(request,
                response);
        }
    }
}
